/**
 * Created by cchen on 2015/4/16.
 */
var Users = mongoose.model('user');
var shareAppName = mongoose.model('mobile_app_shareAppName_restful');
var Share = mongoose.model('mobile_app_user_share_restful');
var NeighbourActivity = mongoose.model('activity_neighbour');
var Question = mongoose.model('question');
var SpecialTopics = mongoose.model('system_specialTopics');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var toolUtil = require('../../common/utils/toolUtil');
var moment = require('moment');
var async = require('async');
var replyAt = mongoose.model('question_replyAt');
var SystemMessage = mongoose.model('system_messages');

exports.shareIsExisted = function (params, callback) {
    Share.findOne(params, callback);
};

exports.addNewShare = function (userId, feedsId, targetApp, feedsType) {
    var newShare = new Share();
    newShare.userId = userId;
    newShare.feedsId = feedsId;
    newShare.shareTo = targetApp;
    newShare.feedsType = feedsType;
    newShare.numberOfClick = 0;
    newShare.save();
    return newShare
};

var typeURL = {
    question: '/pages/static/mobile/partials/share/web/index.html',
    activity: '/pages/static/mobile/partials/share/web/index.html',
    specialTopic: '/pages/static/mobile/partials/share/web/index.html',
    app: "/pages/static/mobile/partials/share/app/index.html",
    app_wx: app_wx
}
var logoURl = "/img/shareLogo.png"

exports.urlGenerate = function (shareObj) {
    return needHttp(AppHost) + typeURL[shareObj.feedsType] + "?shareId=" + shareObj._id;
}

exports.getShareById = function (shareId, callback) {
    Share.findOne({"_id": shareId}, callback);
}

exports.getNeighbourActivity = function (activityId, callback) {
    NeighbourActivity.findOne({_id: activityId}, 'title desc category images replies partake browserCount community dateCreated createdBy activityType deadline', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('partake.user', 'nickName images').populate('createdBy', 'nickName images')
}

exports.getQuestion = function (questionId, callback) {
    Question.findOne({_id: questionId}, 'desc category images replies browserCount community dateCreated createdBy', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('createdBy', 'nickName images')
}

exports.getSpecialTopic = function (topicId, callback) {
    SpecialTopics.findOne({_id: topicId}, callback);
}

exports.updateShareCount = function (shareObj, callback) {
    Share.update({_id: shareObj._id}, {numberOfClick: shareObj.numberOfClick + 1}, callback);
}

//exports.getAppInvitation=function(userId,platform,sysInfo,targetApp,callback){
//    Users.findOne({_id:userId},callback)
//}

exports.shareApp = function (userId, targetApp, callback) {
    var feedsType = 'app'
    exports.shareIsExisted({userId: userId, feedsType: feedsType, shareTo: targetApp}, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, null, targetApp, feedsType)
        }
        exports.getUser(userId, function (err, userObj) {
            if (err) {
                callback(err, null)
            }
            var nowDate = new Date().getTime();
            var community = userObj.community._id + '';
            var sql = 'select voucher_name from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=2 and r.community_id=? and t.id=r.voucher_type_id';

            mysqlUtil.query(sql, [nowDate, nowDate, community], function (err, result) {
                var prize = '奖励';
                if (result.length > 0 && result[0].voucher_name != null) {
                    prize = result[0].voucher_name + '奖励'
                }

                var data = {
                    title: "宝宝树66小区 最有人情味儿的掌上社区",
                    desc: "您的邻居" + userObj.nickName + "邀请您加入" + userObj.community.communityName + "。 邀请码为:" + userObj.invitationCode,
                    image: needHttp(AppHost) + logoURl,
                    //"url":exports.urlGenerate(obj)+"&fromUserId="+userObj._id+"&inviteCode="+userObj.invitationCode,
                    "url": typeURL.app_wx + "?fromUserId=" + userObj._id + "&inviteCode=" + userObj.invitationCode + "&callBackUrl=" + encodeURIComponent(needHttp(AppHost) + typeURL.app),
                    "invitationCode": userObj.invitationCode,
                    prize: prize
                }
                callback(null, {obj: data});
            });
        })
    })
}

var needHttp = function (url) {
    if (url.indexOf("http://") === -1) {
        return "http://" + url;
    }
    return url
}

var imageRefactor = function (url) {
    var array = url.replace("http://", "").split("/");
    var defaultURL = AppHost + logoURl;
    if (array.length <= 1) {
        return defaultURL
    }
    var urlArray = url.split("/");
    var fileArray = urlArray[urlArray.length - 1].split(".");

    if (fileArray.length === 2) {
        fileArray[0] = fileArray[0] + "_120-120"
        var fileStr = fileArray.join(".");
        urlArray[urlArray.length - 1] = fileStr;
        return urlArray.join("/");
    } else {
        return defaultURL
    }
}

var getImageURL = function (images) {
    var imageURL = ''
    if (images && images.length > 0) {
        if (images[0].imageURL.indexOf('http://') === -1) {
            imageURL = fastDfsHostIp + images[0].imageURL
        } else {
            imageURL = images[0].imageURL;
        }
        //if (images[0].imageURL.indexOf('http://res.66xiaoqu.com') != -1) {
        //    imageURL = imageRefactor(imageURL);
        //}
    }
    else {
        imageURL = AppHost + logoURl
    }
    return needHttp(imageURL)
}

var shareData = function (title, desc, images, shareObj, timestamp, userId) {
    return {
        title: title,
        desc: desc ? (desc.length > 200 ? desc.substring(0, 200) : desc) : " ",

        image: getImageURL(images),
        "url": exports.urlGenerate(shareObj) + "&userId=" + userId + "&ver=" + timestamp
    }
}

exports.shareSpectialTopic = function (userId, targetApp, topicId, callback) {
    var feedsType = 'specialTopic'
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: topicId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, topicId, targetApp, feedsType)
        }
        exports.getSpecialTopic(topicId, function (err, topicObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {
                    callback(err, null)
                }
                console.log(topicObj.imageURL);
                callback(null, {obj: shareData(topicObj.title, topicObj.summary, topicObj.imageURL ? [{imageURL: topicObj.imageURL}] : [], obj, topicObj.dateLastModified ? topicObj.dateLastModified.getTime() : topicObj.dateCreated.getTime(), userId)});

            })

        })


    })
}

exports.shareActivity = function (userId, targetApp, activityId, callback) {
    var feedsType = 'activity'
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: activityId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, activityId, targetApp, feedsType)
        }
        exports.getNeighbourActivity(activityId, function (err, actObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {

                }
                callback(null, {obj: shareData(actObj.title, actObj.desc.length > 200 ? actObj.desc.substring(0, 200) : actObj.desc, actObj.images, obj, actObj.dateLastModified ? actObj.dateLastModified.getTime() : actObj.dateCreated.getTime(), userId)});

            })

        })

    })
}

exports.shareQuestion = function (userId, targetApp, questionId, callback) {
    var feedsType = 'question'
    var questionType = {
        'question': '邻里求助',
        'share': '推荐分享',
        'activity': '邻里活动',
        'secondhand': '二手闲置',
        'free': '免费赠送',
        'lostAndFound': '失物招领',
        'advertisement': '邻里广告'
    }
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: questionId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, questionId, targetApp, feedsType)
        }
        exports.getQuestion(questionId, function (err, qustObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {

                }

                logger.info(qustObj.desc.length)

                callback(null, {obj: shareData(qustObj.community.communityName + "的" + questionType[qustObj.category], qustObj.desc.length > 200 ? qustObj.desc.substring(0, 200) : qustObj.desc, qustObj.images, obj, qustObj.dateLastModified ? qustObj.dateLastModified.getTime() : qustObj.dateCreated.getTime(), userId)});

            })

        })

    })
}


exports.getSharedFeeds = function (shareId, userId, callback) {
    Users.findOne({_id: userId}, function (err, user) {
        var typeName = {
            qst: "question",
            act: "activity",
            top: "specialTopic",
            app: "app"

        }
        exports.getShareById(shareId, function (err, obj) {
            if (obj == null || err) {
                callback(err, null);
            } else {

                switch (obj.feedsType) {
                    case typeName.qst:
                        exports.getQuestion(obj.feedsId, function (err, qstObj) {
                            if (err) {
                                callback(err, null);
                            }
                            exports.updateShareCount(obj, function (err, o) {
                                if (err) {
                                    callback(err, null);
                                }
                                qstObj._doc['type'] = 1;
                                qstObj._doc['communityName'] = user.community.communityName;
                                qstObj._doc['categoryName'] = questionCategory[qstObj.category];
                                qstObj._doc['titleDesc'] = '小区邻居发起的';
                                qstObj._doc['replyCount'] = qstObj.replies.length;
                                qstObj._doc['dateCreated'] = qstObj.dateCreated.getTime();
                                qstObj._doc.createdBy._doc.images = qstObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? qstObj.createdBy.images[0].imageURL : fastDfsHostIp + qstObj.createdBy.images[0].imageURL;

                                var replies = [];
                                if (qstObj.replies != null && qstObj.replies.length > 0) {
                                    replies = qstObj.replies.slice(0, 10)
                                }
                                var data = [];
                                async.eachSeries(replies, function (temp, callbackInner) {
                                    if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (user, i) {
                                                    temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                                });
                                            }
                                            var a = {
                                                nickName: temp.repliedBy.nickName,
                                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                                replyDesc: temp.replyDesc,
                                                replyDate: temp.dateReplied.getTime()
                                            };
                                            data.push(a);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else if (temp.replyDesc != null && temp.replyDesc != '') {
                                        var a = {
                                            nickName: temp.repliedBy.nickName,
                                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                            replyDesc: temp.replyDesc,
                                            replyDate: temp.dateReplied.getTime()
                                        };
                                        data.push(a);
                                        callbackInner(err);
                                    } else {
                                        callbackInner()
                                    }
                                }, function (err) {
                                    qstObj._doc['replies'] = data;

                                    callback(null, {obj: qstObj, "host": fastDfsHostIp});
                                });
                            });
                        })
                        break;
                    case typeName.act:
                        exports.getNeighbourActivity(obj.feedsId, function (err, actObj) {
                            if (err) {
                                callback(err, null);
                            }
                            exports.updateShareCount(obj, function (err, o) {
                                if (err) {
                                    callback(err, null);
                                }
                                actObj._doc['type'] = 2;
                                actObj._doc['communityName'] = user.community.communityName;
                                actObj._doc['categoryName'] = '邻里活动';
                                actObj._doc['titleDesc'] = '小区邻居发起的';

                                actObj._doc['dateCreated'] = actObj.dateCreated.getTime();
                                if (actObj.deadline != null)
                                    actObj._doc.deadline = actObj._doc.deadline.getTime();
                                actObj._doc['replyCount'] = actObj.replies.length;
                                actObj._doc.createdBy._doc.images = actObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? actObj.createdBy.images[0].imageURL : fastDfsHostIp + actObj.createdBy.images[0].imageURL;

                                var replies = [];
                                if (actObj.replies != null && actObj.replies.length > 0) {
                                    replies = actObj.replies.slice(0, 10)
                                }
                                var data = [];

                                async.eachSeries(replies, function (temp, callbackInner) {
                                    if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (user, i) {
                                                    temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                                });
                                            }
                                            var a = {
                                                nickName: temp.repliedBy.nickName,
                                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                                replyDesc: temp.replyDesc,
                                                replyDate: temp.dateReplied.getTime()
                                            };
                                            data.push(a);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else if (temp.replyDesc != null && temp.replyDesc != '') {
                                        var a = {
                                            nickName: temp.repliedBy.nickName,
                                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                            replyDesc: temp.replyDesc,
                                            replyDate: temp.dateReplied.getTime()
                                        };
                                        data.push(a);
                                        callbackInner(err);
                                    } else {
                                        callbackInner()
                                    }
                                }, function (err) {
                                    actObj._doc['replies'] = data;

                                    var number = 0;
                                    actObj.partake.forEach(function (par) {
                                        number += par.number;
                                    });

                                    actObj._doc['number'] = number;
                                    var array = actObj.partake.slice(0, 5);

                                    actObj._doc['partakeNum'] = actObj.partake.length;
                                    var partake = [];
                                    array.forEach(function (temp) {

                                        if (temp.partakeType == 2) {
                                            temp._doc.user = {
                                                nickName: temp.name,
                                                images: [{imageURL: wechatImage}]
                                            }
                                        }
                                        var b = {
                                            _id: temp.user._id,
                                            nickName: temp.user.nickName,
                                            images: temp.user.images[0].imageURL.indexOf('http') == 0 ? temp.user.images[0].imageURL : fastDfsHostIp + temp.user.images[0].imageURL,
                                            number: temp.number,
                                            date: temp.time.getTime()
                                        };
                                        partake.push(b);
                                    });

                                    actObj._doc['partake'] = partake;
                                    callback(null, {obj: actObj, "host": fastDfsHostIp});
                                });
                            });
                        })
                        break;
                    case typeName.top:
                        exports.getSpecialTopic(obj.feedsId, function (err, topObj) {
                            if (err) {
                                callback(err, null);
                            }
                            exports.updateShareCount(obj, function (err, o) {
                                if (err) {
                                    callback(err, null);
                                }
                                topObj._doc['type'] = 3;
                                topObj._doc['communityName'] = user.community.communityName;
                                topObj._doc['categoryName'] = '专题';
                                topObj._doc['titleDesc'] = '推荐的有趣';
                                topObj._doc['dateCreated'] = topObj.dateCreated.getTime();
                                callback(null, {obj: topObj, "host": fastDfsHostIp});
                            });
                        })
                        break;
                    case typeName.app:
                        exports.updateShareCount(obj, function (err, o) {
                            if (err) {
                                callback(err, null);
                            }
                            callback(null, {});
                        });
                        break;
                }
            }
        })
    }).populate('community', 'communityName');
}

exports.getUser = function (userId, callback) {
    Users.findOne({_id: userId}, callback).populate("community", "_id communityName")
};


exports.saveInvitationCode = function (userObj, code, callback) {
    Users.update({_id: userObj._id}, {invitationCode: code}, callback);
};

exports.getAppUserShareService = function (userId, callback) {
    Users.findOne({_id: userId}, 'nickName images community invitationCode', function (err, user) {
        var temp = {
            nickName: user.nickName,
            images: user.images[0].imageURL.indexOf('http') == 0 ? user.images[0].imageURL : fastDfsHostIp + user.images[0].imageURL,
            communityName: user.community.communityName,
            invitationCode: user.invitationCode
        }
        callback(err, temp);
    }).populate('community', 'communityName')
};

exports.addPartake = function (input, callback) {

    var partakeNum;

    async.series([
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: input.activityId,
                status: true,
                isValid: true
            }, function (err, result) {
                if (result == null) {
                    callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                } else {
                    if (result.deadline != null && result.deadline.getTime() < new Date().getTime()) {
                        callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                    } else {
                        partakeNum = result.partakeNum;
                        callbackInner();
                    }
                }
            })
        },
        function (callbackInner) {
            neighbourActivity.findOne({
                _id: input.activityId,
                isValid: true,
                'partake.phone': input.phone
            }, 'partake', function (err, result) {
                if (result == null) {
                    var temp = {
                        number: input.number,
                        phone: input.phone,

                        note: input.note
                    };
                    neighbourActivity.update({_id: input.activityId}, {
                        $push: {partake: temp}, partakeNum: partakeNum + 1
                    }, callbackInner)
                } else {

                    neighbourActivity.update({
                        _id: input.activityId,
                        'partake.user': user._id
                    }, {
                        'partake.$.number': input.number,
                        'partake.$.phone': input.phone,
                        'partake.$.note': input.note,
                        'partake.$.time': new Date()
                    }).exec(callbackInner);
                }
            });
        },
        function (callbackInner) {
            neighbourActivity.update({_id: input.activityId}, {dateLastModified: new Date()}, callbackInner)
        },
        function (callbackInner) {
            neighbourActivity.findOne({_id: input.activityId}, '_id title partakeNum createdBy', function (err, result) {

                callbackInner(null, partakeNum);

                if (result.createdBy != user._id) {
                    var temp = new SystemMessage();
                    temp.toUser = result.createdBy;
                    temp.content.questionDesc = '';
                    temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】'
                    temp.content.title = user.nickName;
                    temp.content.contentId = result._id;
                    temp.content.contentType = 'partake';
                    temp.content.questionCreatedBy = result.createdBy;
                    temp.category = 'partake';
                    temp.fromUser = user._id;
                    temp.save();

                    //个推
                    var content = {
                        type: 1,
                        flag: 1,
                        openType: 5,
                        contentId: result._id,
                        createdBy: result.createdBy,
                        desc: user.nickName + '参加了您的活动' + '【' + result.title + '】'
                    };
                    var pushData = {
                        uList: [result.createdBy],
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                }
            });
        }
    ], callback)

};

exports.getPartakesByActivityId = function (pageNo, activityId, callback) {

    var currentPage = 1;
    if (pageNo != '' && pageNo != null) {
        currentPage = pageNo;
    }
    var pageSize = 10;


    NeighbourActivity.findOne({_id: activityId}, "partake", function (err, result) {
        if (result != null && result.partake != null) {
            result.partake.sort(function (a, b) {
                return b.time - a.time;
            })
            currentPage = Number(currentPage);
            result.partake.slice(currentPage * pageSize, (currentPage + 1) * pageSize);
        }

        result.partake.forEach(function (par) {

            if (par.partakeType == 2) {
                par._doc.user = {
                    nickName: par.name,
                    images: [{imageURL: wechatImage}]
                }
            }

            if (par.user.images != null) {
                par.user.images.forEach(function (img) {
                    img.imageURL = img.imageURL.indexOf('http') != -1 ? img.imageURL : fastDfsHostIp + img.imageURL;
                })
            }
        })
        callback(err, result);
    }).populate('partake.user', 'nickName images');
};

exports.joinInActivityByWechatService = function (activityId, input, callback) {
    var partakeNum;
    async.series([
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: activityId,
                status: true,
                isValid: true
            }, function (err, result) {
                logger.info(result);
                if (result == null) {
                    callbackInner({message: '活动已结束'}, null);
                } else {
                    if (result.deadline != null && result.deadline.getTime() < new Date().getTime()) {
                        callbackInner({message: '活动已结束'}, null);
                    } else {
                        partakeNum = result.partakeNum;
                        callbackInner();
                    }
                }
            })
        },
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: activityId,
                isValid: true,
                'partake.phone': input.phone
            }, 'partake', function (err, result) {
                if (result == null) {
                    NeighbourActivity.update({_id: activityId}, {
                        $push: {partake: input}, partakeNum: partakeNum + 1
                    }, callbackInner)
                } else {
                    callbackInner({message: '已经参加过，不能再参加'}, null);
                }
            });
        },
        function (callbackInner) {
            NeighbourActivity.update({_id: activityId}, {dateLastModified: new Date()}, callbackInner)
        },
        function (callbackInner) {
            NeighbourActivity.findOne({_id: activityId}, '_id title partakeNum createdBy', function (err, result) {

                callbackInner(null, partakeNum);

                var temp = new SystemMessage();
                temp.toUser = result.createdBy;
                temp.content.questionDesc = '';
                temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】';
                temp.content.title = input.name;
                temp.content.contentId = result._id;
                temp.content.contentType = 'partake';
                temp.content.questionCreatedBy = result.createdBy;
                temp.category = 'partake';
                temp.save();

                //个推
                var content = {
                    type: 1,
                    flag: 1,
                    openType: 5,
                    contentId: result._id,
                    createdBy: result.createdBy,
                    desc: input.name + '参加了您的活动' + '【' + result.title + '】'
                };
                var pushData = {
                    uList: [result.createdBy],
                    content: content,
                    type: 'user'
                };
                toolUtil.putMessageGetuiPushMQ(pushData);
            });
        }
    ], callback)
};

